package org.thinkinbunny.financial.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.thinkinbunny.financial.R;
import org.thinkinbunny.financial.billentity.UserEntiry;
import org.thinkinbunny.financial.data.DbHelper;
import org.thinkinbunny.financial.data.SyncHelper;
import org.thinkinbunny.financial.http.HttpTools;
import org.thinkinbunny.financial.login.LoginActivity;
import org.thinkinbunny.financial.util.Log;
import org.thinkinbunny.financial.util.DateUtil;
import org.thinkinbunny.financial.util.ShowTools;
import org.thinkinbunny.financial.view.AutoAdjustTextView;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class SyncActivity extends MyActivity implements OnClickListener {
	private ProgressDialog mpDialog;
	Button UpdateBTN, RecoveryTBN;
	AutoAdjustTextView spending_this_month, spending_this_week;
	Cursor cursor;
	DbHelper dbHelper;// =new DbHelper(getApplicationContext(),
	// DbHelper.dBString);
	SQLiteDatabase database;// =dbHelper.getWritableDatabase();
	UserEntiry userEntiry;
	public Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case 0:
				mpDialog.show();
				break;
			case 1:
				mpDialog.dismiss();
				break;

			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		setContentView(R.layout.activity_sync);
		userEntiry = null;
		try {
			Bundle bundle = getIntent().getBundleExtra("userEntiryBundle");

			userEntiry = (UserEntiry) bundle.getSerializable("userEntiry");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			userEntiry = new UserEntiry();
			userEntiry = userEntiry.getUserEntiry(SyncActivity.this);
		}
		INIT_UI();
		super.onCreate(savedInstanceState);
	}

	private void INIT_UI() {
		mpDialog = new ProgressDialog(SyncActivity.this);
		mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置风格为圆形进度条
		mpDialog.setTitle(getString(R.string.dataSync));// 设置标题
		// mpDialog.setIcon(R.drawable.ic_launcher);// 设置图标
		mpDialog.setMessage(getString(R.string.dataSyncmsg));
		mpDialog.setIndeterminate(false);// 设置进度条是否为不明确

		mpDialog.setCancelable(false);// 设置进度条是否可以按退回键取消

		UpdateBTN = (Button) findViewById(R.id.UpdateBTN);
		UpdateBTN.setOnClickListener(this);
		RecoveryTBN = (Button) findViewById(R.id.Recovery_BTN);
		RecoveryTBN.setOnClickListener(this);
		spending_this_month = (AutoAdjustTextView) findViewById(R.id.spending_this_month);
		spending_this_week = (AutoAdjustTextView) findViewById(R.id.spending_this_week);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		if (userEntiry == null) {
			startActivity(new Intent(SyncActivity.this, LoginActivity.class));
			finish();

		}
		dbHelper = new DbHelper(getApplicationContext(), DbHelper.DbName);
		database = dbHelper.getWritableDatabase();
		initData(database);
		database.close();
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Message msgMessage;
		switch (v.getId()) {
		case R.id.UpdateBTN:
			// //msgMessage = mHandler.obtainMessage(0);
			// mHandler.sendMessage(msgMessage);
			if (userEntiry != null) {
				new Thread() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Sync2Server(userEntiry);
						super.run();
					}
				}.start();
			} else {
				startActivity(new Intent(SyncActivity.this, LoginActivity.class));
				finish();
			}

			// SyncFromServer();
			// msgMessage = mHandler.obtainMessage(1);
			// mHandler.sendMessage(msgMessage);
			break;
		case R.id.Recovery_BTN:
			// msgMessage = mHandler.obtainMessage(0);
			// mHandler.sendMessage(msgMessage);
			// Sync2Server();

			if (userEntiry != null) {
				new Thread() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						SyncFromServer(userEntiry);
						super.run();
					}
				}.start();
			} else {
				startActivity(new Intent(SyncActivity.this, LoginActivity.class));
				finish();
			}
			break;

		default:
			break;
		}
		super.onClick(v);
	}

	private boolean Sync2Server(UserEntiry userEntiry) {

		final SyncHelper syncHelper = new SyncHelper(SyncActivity.this);
		Message msgMessage = mHandler.obtainMessage(0);
		mHandler.sendMessage(msgMessage);
		Log.i("Lanucher", syncHelper.getJsonArrayFromDB().toString());
		try {

			JSONArray maindata = HttpTools.HttpPostData(
					syncHelper.getJsonArrayFromDB(), "updateMain", userEntiry);
			JSONArray accountdata = HttpTools.HttpPostData(
					syncHelper.getJsonArrayFromDB_AccountTable(),
					"updateAccount", userEntiry);
			JSONArray projectdata = HttpTools.HttpPostData(
					syncHelper.getJsonArrayFromDB_ProjectTable(),
					"updateProject", userEntiry);
			JSONArray typedata = HttpTools.HttpPostData(
					syncHelper.getJsonArrayFromDB_TypeTable(), "updateType",
					userEntiry);
			Log.i("SyncTest", accountdata.toString());
			// HttpTools.sendPostRequest(null, syncHelper.getJsonArrayFromDB());
		} catch (Exception e) {
			// TODO Auto-generated catch blockto

			ShowTools.toastInThread(getString(R.string.dataSyncUpErr));
			msgMessage = mHandler.obtainMessage(1);
			mHandler.sendMessage(msgMessage);
			e.printStackTrace();
			return false;
		}
		msgMessage = mHandler.obtainMessage(1);
		mHandler.sendMessage(msgMessage);
		ShowTools.toastInThread(getString(R.string.dataSyncUpOk));
		return true;

	}

	private boolean SyncFromServer(UserEntiry userEntiry) {
		final SyncHelper syncHelper = new SyncHelper(SyncActivity.this);
		// Log.i("Lanucher", syncHelper.getJsonArrayFromDB().toString());
		Message msgMessage = mHandler.obtainMessage(0);
		mHandler.sendMessage(msgMessage);
		// UserEntiry userEntiry = UserEntiry.getUserEntiry(SyncActivity.this);
		try {
			JSONArray updateMainTable = HttpTools.HttpGetData(
					"updateMainTable", userEntiry);
			JSONArray updateAccountTable = HttpTools.HttpGetData(
					"updateAccountTable", userEntiry);
			JSONArray updateProjectTable = HttpTools.HttpGetData(
					"updateProjectTable", userEntiry);
			JSONArray updateTypeTable = HttpTools.HttpGetData(
					"updateTypeTable", userEntiry);
			if (updateMainTable != null && updateAccountTable != null
					&& updateProjectTable != null && updateTypeTable != null) {
				// ShowTools.toastInThread("sync");
				if (syncHelper
						.SyncDataFromServer(updateMainTable,
								updateAccountTable, updateProjectTable,
								updateTypeTable)) {
					ShowTools.toastInThread(getString(R.string.dataSyncOk));
				} else {
					ShowTools.toastInThread(getString(R.string.dataSyncErr));
				}
				;
			} else {
				ShowTools.toastInThread(getString(R.string.dataSyncException));
			}
			// JSONArray accountdata= HttpTools.HttpPostData(
			// syncHelper.getJsonArrayFromDB_AccountTable(),"updateAccount");
			// //JSONArray projectdata=HttpTools.HttpPostData(
			// syncHelper.getJsonArrayFromDB_ProjectTable(),"updateProject");
			// JSONArray typedata= HttpTools.HttpPostData(
			// syncHelper.getJsonArrayFromDB_TypeTable(),"updateType");
			Log.i("SyncActivity->>SyncFromServer", updateMainTable.toString());
			// HttpTools.sendPostRequest(null, syncHelper.getJsonArrayFromDB());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			msgMessage = mHandler.obtainMessage(1);
			mHandler.sendMessage(msgMessage);
			ShowTools.toastInThread(getString(R.string.dataSyncRecoveryErr));
			e.printStackTrace();
			return false;
		}
		msgMessage = mHandler.obtainMessage(1);
		mHandler.sendMessage(msgMessage);
		ShowTools.toastInThread(getString(R.string.dataSyncRecoveryOk));
		return true;

	}

	public void initData(SQLiteDatabase database) {
		// database=dbHelper.getWritableDatabase();
		Cursor cursor = database.rawQuery("select * from accountInfo", null);
		// ArrayList<HashMap<String, Object>> listItem = new
		// ArrayList<HashMap<String, Object>>();
		//
		// listViewAdapter = new ListViewAdapter(getApplicationContext(),
		// R.layout.list_items, cursor, new String[] { "balance",
		// "billType", "date", "time" }, new int[] {
		// R.id.billMoneyTextView, R.id.billTypeTextView,
		// R.id.billTimeTextView });
		// // 添加并且显示
		// billListView.setAdapter(listViewAdapter);
		final Cursor getCursor = cursor;
		float balance = 0.0f;
		float monthBalance = 0.0f;
		ArrayList week = DateUtil.getWeekBill();
		while (getCursor.moveToNext()) {
			if (week.contains(getCursor.getString(getCursor
					.getColumnIndex("date")))) {
				balance += getCursor.getFloat(getCursor
						.getColumnIndex("balance"));
			}
			if (getCursor.getString(getCursor.getColumnIndex("date"))
					.startsWith(DateUtil.getMonthBill())) {
				monthBalance += getCursor.getFloat(getCursor
						.getColumnIndex("balance"));
			}

		}
		spending_this_week.setText(balance + "￥");
		spending_this_month.setText(monthBalance + "￥");

		// 添加点击

		// billListView.setOnCreateContextMenuListener(new
		// OnCreateContextMenuListener() {
		//
		// public void onCreateContextMenu(ContextMenu menu, View
		// v,ContextMenuInfo menuInfo) {
		// menu.setHeaderTitle("账单操作");
		// menu.add(0, 0, 0, "删除");
		// menu.add(0, 1, 0, "编辑");
		// }
		//
		//
		// });

	}
}
